package main

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	uuid "github.com/satori/go.uuid"
	"log"
	"os"
	"os/signal"
	"project05_web/src/global"
	"project05_web/src/initalize"
	"project05_web/src/utils"
	"project05_web/src/utils/register/consul"
	myvarlidator "project05_web/src/varlidator"
	"syscall"
)

func main() {
	//初始化翻译器，这部分可放在main.go或router.go中
	if err := utils.InitTrans("zh"); err != nil { //汉化报错信息
		log.Fatalf("init trans failed, err:%v\n", err)
		return
	}

	initalize.InitConfig() //初始化配置
	initalize.InitConn()   //初始化grpc连接
	initalize.InitRedisDb()
	myRouter := initalize.InitUserRouter()
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", myvarlidator.CheakMobile)
		_ = v.RegisterValidation("identify", myvarlidator.CheakIdentify)
	}

	register_client := consul.NewRegistryClient(global.SrvConfig.ConsulInfo.Host, global.SrvConfig.ConsulInfo.Port)
	serviceId := fmt.Sprintf("%s", uuid.NewV4())
	err := register_client.Register(global.SrvConfig.Host, global.SrvConfig.Port, global.SrvConfig.Name, global.SrvConfig.Tags, serviceId)
	if err != nil {
		panic(err)
	}

	go func() {
		if err := myRouter.Run(fmt.Sprintf("%s:%d", global.SrvConfig.Host, global.SrvConfig.Port)); err != nil {
			panic(err)
		}
	}()
	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = register_client.DeRegister(serviceId); err != nil {
		panic(err)
	} else {
		fmt.Println("注销成功")
	}
}
